//
//  LRXPocketMoneyController.m
//  路人侠
//
//  Created by zhangxulong on 4/22/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXPocketMoneyController.h"
#import "LRXPocketModle.h"
#import "WalletTableViewCell.h"
#import "LRXSettingViewController.h"
#import "MJRefreshHeader.h"
#import "MJRefresh.h"
#import "LRXWithdrawController.h"
@interface LRXPocketMoneyController ()
{
    UITableView * _WalletTabelView;
}
@property (nonatomic,copy) NSString * nextPage;
@property (nonatomic,assign) NSInteger  nextPageFlag;
@property (nonatomic,strong) NSMutableArray * accpItems;
@property (nonatomic,weak) UILabel * balanceLabel;
@end
@implementation LRXPocketMoneyController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的钱包";
    UIButton * rightnbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightnbtn.bounds = CGRectMake(0, 0, 40 * wScale, 35 * hScale);
    rightnbtn.tag = 1001;
    [rightnbtn setImage:[UIImage imageNamed:@"hover"] forState:UIControlStateNormal];
    [rightnbtn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightnbtn];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    self.nextPageFlag = 1;
    self.nextPage = @"";
    [self getPocketInfo];
    [self initTableView];
    [self layoutHeadView];
    [self getBalanceLabel];
    [MBProgressHUD showMessage:nil];
    
}
- (NSMutableArray *)accpItems
{
    if (_accpItems == nil) {
        _accpItems = [NSMutableArray array];
    }
    return _accpItems;
}
-(void)initTableView{
    self.view.backgroundColor = [UIColor whiteColor];
    _WalletTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0.0,293*hScale,self.view.frame.size.width,self.view.frame.size.height-293*hScale) style:UITableViewStylePlain];
    _WalletTabelView.delegate = self;
    _WalletTabelView.dataSource = self;
    _WalletTabelView.showsVerticalScrollIndicator=YES;
    _WalletTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _WalletTabelView.rowHeight = 123 * hScale;
    [self.view addSubview:_WalletTabelView];

}

#pragma mark - TableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _accpItems.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    static NSString * WalletCell = @"WalletCell";
    LRXPocketModle * pocketModel = _accpItems[indexPath.row];
    
    WalletTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:WalletCell];
    if (cell == nil) {
        cell = [[WalletTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WalletCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSString *subDate  = pocketModel.date;
    subDate = [self subStringForm:subDate];
    subDate = [self subStringTo:subDate];
    cell.date = subDate;
    cell.money = [NSString stringWithFormat:@"+%.2lf元",(float)[self stringToDouble:pocketModel.total_price]];
    cell.image = @"help";
    
    
    double price = [self stringToDouble:pocketModel.total_price] * 0.9;
    price = round(price * 100) / 100;
    double tip =  [self stringToDouble:pocketModel.total_price] - price;
    cell.detail = [NSString stringWithFormat:@"物价%.2lf元,小费%.2lf元",(float)price,(float)tip];
    return cell;
}


-(void)layoutHeadView{
    
    UIView *view = [[UIView alloc]init];

    view.backgroundColor = mainColor;
    view.frame = CGRectMake(0, 0, self.view.frame.size.width, 253 * hScale);

    
    UILabel * title = [[UILabel alloc]init];
    title.frame = CGRectMake(34* wScale, 70 * hScale, 200 * wScale, 19 * hScale);
    title.font = [UIFont systemFontOfSize:30 * wScale];
    title.textColor = [UIColor whiteColor];
    title.text = @"钱包余额";
    

    UILabel * mLabel = [[UILabel alloc]init];
    mLabel.frame = CGRectMake(39 * wScale,CGRectGetMaxY(title.frame) + 80 * hScale, 21 * wScale, 25 * hScale);
    mLabel.font = [UIFont systemFontOfSize:25*wScale];
    mLabel.text = @"¥";
    mLabel.textColor = [UIColor whiteColor];
    
    
    UILabel *balanceLabel= [[UILabel alloc]init];
    balanceLabel.frame = CGRectMake(CGRectGetMaxX(mLabel.frame)+29*wScale, 153*hScale, 189*wScale, 52*hScale);
    balanceLabel.font = [UIFont systemFontOfSize:34*wScale];
    balanceLabel.text = @"0000";
    balanceLabel.textColor = [UIColor whiteColor];
    self.balanceLabel = balanceLabel;
    
    
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    but.frame = CGRectMake(CGRectGetMaxX(balanceLabel.frame) + 280 * wScale, 112 * hScale, 60 * hScale, 60 * hScale);
    [but setImage:[UIImage imageNamed:@"morePocket"] forState:UIControlStateNormal];
    but.tag = 1000;
    [but addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
    

    UIView *dView = [[UIView alloc]init];
    dView.frame = CGRectMake(0,CGRectGetMaxY(view.frame),self.view.frame.size.width,50*hScale);
    dView.backgroundColor = [UIColor whiteColor];
    
    
    UILabel *dLabel = [[UILabel alloc]init];
    dLabel.frame = CGRectMake(54 * wScale,5 * hScale,200 * wScale,40 * hScale);
    dLabel.text = @"收支明细";
    dLabel.font = [UIFont systemFontOfSize:20 * hScale];
    dLabel.textColor = [UIColor colorWithRed:95 green:95 blue:95];
    
    
    [self.view addSubview:dView];
    [dView addSubview:dLabel];
    
    
    [view addSubview:title];
    [view addSubview:mLabel];
    [view addSubview:balanceLabel];
    [view addSubview:but];
    [self.view addSubview:view];
}
#pragma mark - 推出新的界面
/**
 *  推出新的界面
 *
 *  @param btn tag 1000 表示 进入提现界面
 *                 1001 表示 进入账户设置
 */
-(void)action:(UIButton *)btn{
    if (btn.tag == 1000) {
        LRXWithdrawController *view = [[LRXWithdrawController alloc]init];
        view.zfbAcount = @"1043657234@qq.com";
        view.balance = self.balanceLabel.text;
        [self.navigationController pushViewController:view animated:YES];
    }
    else if (btn.tag == 1001)
    {
        UIAlertController * alerController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction * setAction = [UIAlertAction actionWithTitle:@"支付管理" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController pushViewController:[LRXSettingViewController new] animated:YES];
        }];
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alerController addAction:setAction];
        [alerController addAction:cancelAction];
        [self presentViewController:alerController animated:YES completion:nil];
        
       
    }
}

- (void)getBalanceLabel
{
    NSURLSession * session = [NSURLSession  sharedSession];
    NSURL * urlStr = [NSURL URLWithString:jabvdpUrl];
    NSURLSessionDataTask * dataSession = [session dataTaskWithURL:urlStr completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response) {
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                NSInteger statusCode = [dic[@"data"][@"status_code"] integerValue];
                
                if (statusCode == 1) {
                    CGFloat ba = [dic[@"data"][@"ba"] floatValue];
                    self.balanceLabel.text = [NSString stringWithFormat:@"%.2lf",ba / 100];
                }
                else if(statusCode == 2)
                {
                    [MBProgressHUD showError:@"请重新登录"];
                }
            }
            else if(error)
            {
                [MBProgressHUD showError:@"网络连接失败"];
            }

        });
    }];
    
    [dataSession resume];
}
- (void)getPocketInfo
{
    NSDictionary * paramDic = @{@"page":_nextPage};
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    [manger GET:pockerUrl parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            if ([responseObject[@"data"][@"status_code"] isEqualToString:@"1"]) {
                
                self.nextPage = responseObject[@"data"][@"next_page"];
                
                if(self.nextPageFlag == 1)
                {
                    
                    for (NSDictionary * pocketDic in responseObject[@"data"][@"dataset"]) {
                        LRXPocketModle * model = [LRXPocketModle myPocketModel:pocketDic];
                        [self.accpItems addObject:model];
                    }
                    [_WalletTabelView reloadData];
                }
                else{
                    [(MJRefreshStateHeader *)self->_WalletTabelView.mj_footer setTitle:@"少侠没有更多数据" forState:MJRefreshStateRefreshing];
                }
            }
            
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}
-(NSString *)subStringTo:(NSString *)str{

    return [str substringFromIndex:5];

}
-(NSString *)subStringForm:(NSString *)str{

    return [str substringToIndex:9];
    
}
-(double)stringToDouble:(NSString *)str{
    
    return [str doubleValue];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)popRootController
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
